package com.zby.admin.service.imp;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zby.admin.mapper.ProductMapper;
import com.zby.admin.pojo.Products;
import com.zby.admin.pojo.Images;
import com.zby.admin.pojo.dto.ProductsDto;
import com.zby.admin.pojo.vo.ProductVo;
import com.zby.admin.service.ImagesService;
import com.zby.admin.service.ProductService;
import com.zby.utils.PageResult;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class ProductServiceImp extends ServiceImpl<ProductMapper, Products> implements ProductService {
    @Resource
    private ImagesService imagesService;
    @Override
    public boolean addData(ProductsDto productsDto, HttpServletRequest request) {
        Products products = new Products();
        
        // 修复空指针异常：检查userId是否为空
        Object userIdObj = request.getSession().getAttribute("userId");
        if (userIdObj != null) {
            products.setUserId(userIdObj.toString());
        } else {
            // 如果session中没有userId，
            // 使用默认用户ID，或根据业务需求处理
            products.setUserId((String) userIdObj);
        }
        
        products.setTitle(productsDto.getTitle());
        products.setHomeImage(productsDto.getHomeImage());
        products.setPrice(productsDto.getPrice());
        products.setCategoryId(productsDto.getCategoryId());
        products.setCategoryTypeId(productsDto.getCategoryTypeId());
        products.setBrandId(productsDto.getBrandId());
        products.setStatus(productsDto.getStatus());
        products.setNumber(productsDto.getNumber());
        products.setSold(productsDto.getSold());
        products.setDescription(productsDto.getDescription());
        products.setCondition(productsDto.getCondition());

        // 先保存商品以获取ID
        boolean saved = this.save(products);
        // 查询id
        // 确保在保存成功后正确获取商品ID
        if (saved && productsDto.getImage() != null && !productsDto.getImage().isEmpty()) {
            // 设置图片列表，关联商品ID
            Long productId = products.getId(); // 获取保存后的商品ID
            List<Images> imagesList = productsDto.getImage().stream()
                    .map(url -> {
                        Images productImage = new Images();
                        productImage.setUrl(url);
                        productImage.setProductId(Math.toIntExact(productId)); // 使用保存后的商品ID
                        return productImage;
                    })
                    .collect(Collectors.toList());
            // 保存图片列表
            imagesService.saveBatch(imagesList);
        }

        return saved;
    }
    
    @Override
    public PageResult<ProductVo> selectList(Integer page, Integer pageSize) {
        // 计算偏移量
        int offset = (page - 1) * pageSize;
        
        // 构造查询条件
        QueryWrapper<Products> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 0); // 只查询未删除的数据
        queryWrapper.orderByDesc("create_time"); // 按创建时间倒序排列
        
        // 查询总数
        long total = this.count(queryWrapper);
        
        // 分页查询商品数据
        List<Products> productsList = this.list(queryWrapper.last("limit " + offset + ", " + pageSize));
        
        // 转换为ProductVo列表
        List<ProductVo> productVoList = productsList.stream().map(products -> {
            ProductVo productVo = new ProductVo();
            BeanUtils.copyProperties(products, productVo);
            
            // 查询关联的图片
            QueryWrapper<Images> imagesQueryWrapper = new QueryWrapper<>();
            imagesQueryWrapper.eq("product_id", products.getId());
            imagesQueryWrapper.eq("deleted", 0);
            List<Images> imagesList = imagesService.list(imagesQueryWrapper);
            
            // 提取图片URL列表
            List<String> imageUrls = imagesList.stream()
                    .map(Images::getUrl)
                    .collect(Collectors.toList());
            
            productVo.setImage(imageUrls);
            return productVo;
        }).collect(Collectors.toList());
        
        // 封装分页结果
        return new PageResult<>(page, pageSize, total, productVoList);
    }
    
    @Override
    public PageResult<ProductVo> selectListByUserId(Long userId, Integer page, Integer pageSize) {
        // 计算偏移量
        int offset = (page - 1) * pageSize;
        
        // 构造查询条件
        QueryWrapper<Products> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 0); // 只查询未删除的数据
        queryWrapper.eq("user_id", userId); // 根据用户ID查询
        queryWrapper.orderByDesc("create_time"); // 按创建时间倒序排列
        
        // 查询总数
        long total = this.count(queryWrapper);
        
        // 分页查询商品数据
        List<Products> productsList = this.list(queryWrapper.last("limit " + offset + ", " + pageSize));
        
        // 转换为ProductVo列表
        List<ProductVo> productVoList = productsList.stream().map(products -> {
            ProductVo productVo = new ProductVo();
            BeanUtils.copyProperties(products, productVo);
            
            // 查询关联的图片
            QueryWrapper<Images> imagesQueryWrapper = new QueryWrapper<>();
            imagesQueryWrapper.eq("product_id", products.getId());
            imagesQueryWrapper.eq("deleted", 0);
            List<Images> imagesList = imagesService.list(imagesQueryWrapper);
            
            // 提取图片URL列表
            List<String> imageUrls = imagesList.stream()
                    .map(Images::getUrl)
                    .collect(Collectors.toList());
            
            productVo.setImage(imageUrls);
            return productVo;
        }).collect(Collectors.toList());
        
        // 封装分页结果
        return new PageResult<>(page, pageSize, total, productVoList);
    }
    
    @Override
    public boolean deleteById(Long id) {
        // 先删除关联的图片（逻辑删除）
        QueryWrapper<Images> imagesQueryWrapper = new QueryWrapper<>();
        imagesQueryWrapper.eq("product_id", id);
        imagesService.remove(imagesQueryWrapper);
        
        // 删除商品（逻辑删除）
        return this.removeById(id);
    }
    
    @Override
    public boolean updateData(ProductsDto productsDto) {
        // 更新商品信息
        Products products = new Products();
        products.setId(productsDto.getId());
        products.setTitle(productsDto.getTitle());
        products.setHomeImage(productsDto.getHomeImage());
        products.setPrice(productsDto.getPrice());
        products.setCategoryId(productsDto.getCategoryId());
        products.setCategoryTypeId(productsDto.getCategoryTypeId());
        products.setBrandId(productsDto.getBrandId());
        products.setStatus(productsDto.getStatus());
        products.setNumber(productsDto.getNumber());
        products.setSold(productsDto.getSold());
        products.setDescription(productsDto.getDescription());
        products.setCondition(productsDto.getCondition());
        products.setRemark(productsDto.getRemark());
        
        boolean updated = this.updateById(products);
        
        // 更新图片信息
        if (updated) {
            // 先删除原有的图片（逻辑删除）
            QueryWrapper<Images> imagesQueryWrapper = new QueryWrapper<>();
            imagesQueryWrapper.eq("product_id", productsDto.getId());
            imagesService.remove(imagesQueryWrapper);
            
            // 如果新的图片列表不为空，则添加新图片
            if (!CollectionUtils.isEmpty(productsDto.getImage())) {
                List<Images> imagesList = productsDto.getImage().stream()
                        .map(url -> {
                            Images image = new Images();
                            image.setUrl(url);
                            image.setProductId(Math.toIntExact(productsDto.getId()));
                            return image;
                        })
                        .collect(Collectors.toList());
                
                imagesService.saveBatch(imagesList);
            }
        }
        
        return updated;
    }
}